/*
Copyright 2008  Four Roads LLC conact@4-roads.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections;
using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Components.SearchBarrel;

namespace FourRoads.Links
{
	using DataProvider;
	/// <summary>
	/// Summary description for ResLinkSearchJob.
	/// </summary>
	public class ResLinkSearchJob : SearchJob
	{
		public ResLinkSearchJob()
		{

		}

		public override void IndexPosts(int setSize, int settingsID)
		{
			ResLinkDataProvider dp = ResLinkDataProvider.Instance();

			PostSet postSet =  dp.SearchReindexPosts(setSize, settingsID);

			foreach (Post post in postSet.Posts) 
			{
				Hashtable words = new Hashtable();
				int totalBodyWords = 0;

				ResLinkLink link = post as ResLinkLink;
				if(link != null)
				{
					// Process the post subject
					//
					words = Index(link.Subject, words, WordLocation.Subject, settingsID);

					// Process the post body
					//
					words = Index(link.Body, words, WordLocation.Body, settingsID);

					// Get a count of the total words in the body
					//
					totalBodyWords = SearchTerms.CleanSearchTerms(link.Body).Length;
					InsertIntoSearchBarrel(words, link, settingsID, totalBodyWords);
				}
			}
		}

		protected override double CalculateWordRank(Word word, Post post, int totalBodyWords)
		{
			int wordOccurrence = 0;
			int wordInSubject =0;
			// Word weighting:
			// ============================
			// Word Occurence:      10
			// Rating:				5
			// Word in Subject:     10
			//                    ----
			// Max score:           25

			// Assign a score for how many times the word occurs in the post
			//
			wordOccurrence = word.Occurence * 2;

			if (wordOccurrence > 10)
				wordOccurrence = 10;

			double replyWeight = 0;

			if (post is IThread) 
			{
				IThread thd = (IThread)post;
		
				if ( thd.RatingAverage > -1 )
					replyWeight = thd.RatingAverage;
			}

			if (post.Subject.IndexOf(word.Name , 0 ) != -1)
				wordInSubject = 10;

			// Calculate the final weight of the word
			//
			return (wordOccurrence + replyWeight + wordInSubject ) / 25f;
		}
	}
}
